<template>
  <view class="feeding-wrapper">
    <view class="order-search">
      <u-search placeholder="请输入加料商品名称" v-model="pageInfo.keyword" clearable bgColor="#fff" borderColor="#e5e5e5"
        :showAction="false" @search="handleSearch" @clear="handleReset"></u-search>
      <view class="flex-row" style="flex:2">
        <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
        <!-- <u-button :plain="true" text="重置" @click="handleReset"></u-button> -->
      </view>
    </view>
    <view class="feeding-table">
      <view class="feeding-list">
        <scroll-view scroll-y="true" ref="scrollView" style="height: 100%; width: 100%"
          @scrolltolower="onScrollToLower">
          <template v-if="list.length>0">
            <view class="item-card" v-for="(item, index) in list" :key="index">
              <view class="item-card-top">
                <view class="left-area">
                  <image class="item-icon" src="../../../static/imgs/jialiao.png" mode=""></image>
                  <view class="text-group">
                    <text class="item-name">{{ item.name }}</text>
                    <view class="middle-area">
                      <text class="status">
                        状态：
                        <text class="status-dot"
                          :class="{ enable: item.status == 1, disable: item.status == 0 }"></text>
                        {{ item.status === 1 ? '启用' : '禁用' }}
                      </text>
                      <view class="info-item">售价：¥{{ item.price }}</view>
                      <view class="info-item" style="margin-left: 30px;">库存：{{ item.stock }}</view>
                     <!-- <view class="info-item" style="flex:2">创建时间：{{ item.createDate }}</view>
                      <view class="info-item" style="flex:2">最近更新时间：{{ item.lastUpdateDate }}</view> -->
                    </view>
                  <view class="middle-area" style="margin-top: 10px;">
                    <view class="info-item" style="flex:2">创建时间：{{ item.createDate }}</view>
                    <view class="info-item" style="flex:2">最近更新时间：{{ item.lastUpdateDate }}</view>
                  </view>

                  </view>
                </view>
              </view>

              <!-- 右侧：操作按钮 -->
              <view class="right-area">
                <view class="right-btn">
                  <view class="operate-btn edit" @click="handleEdit(item)">
                    <image src="../../../static/imgs/edit.png" mode=""></image>
                    编辑
                  </view>
                  <view class="operate-btn" @click="handleDisable(item)" v-if="item.status == 1">
                    <image src="../../../static/imgs/disable.png" mode=""></image> 禁用
                  </view>
                  <view class="operate-btn" @click="handleDisable(item)" v-if="item.status == 0">
                    <image src="../../../static/imgs/enable.png" mode=""></image> 启用
                  </view>
                  <view class="operate-btn" @click="handleDelete(item)">
                    <image src="../../../static/imgs/trash.png" mode=""></image> 删除
                  </view>
                </view>
              </view>
            </view>

          </template>
          <template v-else>
            <view class="empty-box" style="text-align: center;padding-top: 12vh;">
              <image src="/src/static/imgs/emptyW.png" mode="widthFix" style="width: 240px;"></image>
              <view class="text1" style="color: #999;">暂无数据</view>
            </view>
          </template>
        </scroll-view>
      </view>
      <view class="detail-foot">
        <view class="foot-btn" style="margin: auto">
          <view class="order-btn" @click="contentClick">新增加料</view>
        </view>
      </view>
    </view>
  </view>
  <u-popup :show="show" @close="popupCancel" :round="10" mode="center">
    <view class="popup-cons">
      <view class="applyfor-tit">
        {{showTitle}}
      </view>
      <view class="applyfor-info">
        {{showInfo}}
      </view>
      <view class="button-group">
        <button class="cancel-btn" @click="popupCancel">取消</button>
        <button class="pay-btn" @click="popupSure">确认</button>
      </view>
    </view>
  </u-popup>
</template>
<script setup>
  import {
    ref,
    computed,
    onMounted,
    reactive
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getAddonOptions,
    deleteAddonOptions,
    updateAddonOptions
  } from '@/requests/apis/products'
  let show = ref(false)
  let showType = ref()
  let showTitle = ref()
  let showInfo = ref()
  let itemData = ref()
  let list = ref([])
  let pageInfo = reactive({
    total: 0,
    page: 1,
    limit: 20,
    keyword: '',
  });
  onMounted(() => {
    getData()
  })
  const onScrollToLower = () => {
    if (pageInfo.page * pageInfo.limit < pageInfo.total && list.value.length >= 20) {
      pageInfo.page++;
      getData('add');
    }
  }
  const getData = async (type) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    let res = await getAddonOptions({
      ...pageInfo
    })
    pageInfo.total = res.Result.total
    if (type === 'add') {
      list.value = [...list.value, ...(res.Result.records || [])];
    } else {
      list.value = res.Result.records || [];
    }
    uni.hideLoading()
  }
  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    getData()
  }
  const handleReset = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    getData()
  }
  const contentClick = () => {
    uni.navigateTo({
      url: '/pages/products/feeding/formAdd',
    })
  }
  const handleEdit = (item) => {
    uni.navigateTo({
      url: `/pages/products/feeding/formAdd?infoList=${encodeURIComponent(
      JSON.stringify(item),
    )}`,
    })
  }
  const handleDisable = (item) => {
    show.value = true;
    showType.value = 2;
    showTitle.value = item.status === 1 ? '确认禁用' : '确认启用'
    showInfo.value = item.status === 1 ? `是否确认禁用“${item.name}”，引用商品将在点餐前台不显示该加料商品。` :
      `已引用商品将在点餐前台展示该加料商品。是否确认启用“${item.name}”？`
    let data = JSON.parse(JSON.stringify(item))
    data.status = data.status === 1 ? 0 : 1
    itemData.value = data
  }
  const handleDelete = (item) => {
    show.value = true;
    showType.value = 1;
    showTitle.value = '确认删除'
    showInfo.value = ` 删除“${item.name}”后，所有关联的商品加料将被永久删除，且无法恢复。请确认是否继续？`
    itemData.value = item

  }
  // 弹窗取消
  const popupCancel = () => {
    show.value = false
  }
  // 弹窗确认
  const popupSure = () => {
    show.value = false
    if (showType.value == 1) {
      deleteAddonOptions({
          ids: [itemData.value.id],
        })
        .then((a) => {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000,
            success() {
              setTimeout(() => {
                getData()
              }, 2000)
            },
          })
        })
        .catch((error) => {
          uni.hideLoading()
        })
    } else {
      let tit = itemData.value.status === 1 ? '启用' : '禁用'
      updateAddonOptions({
          id: itemData.value.id,
          status: itemData.value.status,
          name: itemData.value.name,
          stock: itemData.value.stock,
          price: itemData.value.price
        })
        .then((a) => {
          uni.showToast({
            title: `${tit}成功`,
            icon: 'success',
            success() {
              setTimeout(() => {
                getData('refresh')
              }, 1500)
            },
          })
        })
        .catch((error) => {
          uni.hideLoading()
        })
    }
  }
</script>
<style lang="scss" scoped>
  .feeding-wrapper {
    display: flex;
    // flex: 1;
    overflow: hidden;
    flex-direction: column;
    height: 100%;
    .order-search {
      display: flex;
      background-color: #fff;
      margin: 10px 10px 0;
      padding: 12px 145px 12px 20px;
      box-sizing: border-box;

      :deep(button) {
        width: 74px;
        height: 38px;
        margin-left: 11px;
        margin-right: 0;
        border-radius: 100px;
      }
    }

    .feeding-table {
     flex: 1;
     height: 100%;
     overflow: hidden;
     display: flex;
     flex-direction: column;


      .feeding-list {
        flex: 1;
        overflow: hidden;

        .item-card {
          padding: 21px 10px 10px 22px;
          box-sizing: border-box;
          border-radius: 8px;
          margin: 10px;
          background: #FFFFFF;

          .item-card-top {
            display: flex;
          }

          .left-area {
            display: flex;
            align-items: center;
            width: 100%;

            .item-icon {
              width: 40px;
              height: 40px;
              margin-right: 19px;
            }

            .text-group {
              display: flex;
              flex-direction: column;
              flex: 1;

              .item-name {
                font-weight: 500;
                font-size: 16px;
                color: #333333;
                line-height: 22px;
                margin-bottom: 6px;
              }

              .middle-area {
                display: flex;
                flex-wrap: nowrap;
                // gap: 40px;
                font-size: 14px;
                color: #666;

                .info-item {
                  font-weight: 400;
                  font-size: 14px;
                  color: #666666;
                }

                .status {
                  font-weight: 400;
                  font-size: 14px;
                  color: #666666;
                  line-height: 20px;
                  margin-right: 30px;

                  .status-dot {
                    display: inline-block;
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    margin-right: 4px;

                    &.enable {
                      background-color: #52C41A;
                    }

                    &.disable {
                      background-color: #F32F1D;
                    }
                  }
                }
              }



            }
          }


          /* 右侧区域：操作按钮 */
          .right-area {
            display: flex;
            justify-content: flex-end;

            .right-btn {
              display: flex;
              gap: 10px;
            }

            .operate-btn {
              display: flex;
              align-items: center;
              padding: 6px 12px;
              border-radius: 4px;
              box-sizing: border-box;
              font-weight: 400;
              font-size: 14px;
              color: #0F90FD;
              background: rgba(15, 144, 253, 0.1);
              border-radius: 100px;
              margin-top: 12px;

              image {
                width: 16px;
                height: 16px;
                margin-right: 2px;
              }
            }
          }
        }
      }

      .detail-foot {
        margin-left: 10px;
        margin-right: 10px;
        margin-top: auto;
        position: static;
        bottom: 0;
        background: #ffffff;
        box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
        border-radius: 10px;
        height: 54px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;
      }
    }
  }
</style>
